<?php
/**
 * Created by IntelliJ IDEA.
 * User: wanglu
 * Date: 2017/7/19
 * Time: 14:13
 */
/**
 * Created by wanglu on 2017/7/19.
 */
class App extends AdminBase {

    const ALI_I18N_BUCKET = "slightech-i18n";

    function __construct() {
        parent::__construct();
        $this->load->model('app_model');
        $this->load->library('Oss');
        $this->load->config('aliyun_oss');
    }

    public function i18n() {
        $op = $this->input->get('op');
        if (empty($op)) {
            $this->showView("app_i18n");
        } else {
            $search = $this->input->post("search");
            $order = $this->input->post("order");
            $orderIndex = $order[0]["column"];
            $asc_or_desc =  $order[0]["dir"];
            $orderby = array();
            switch ($orderIndex) {
                case 1:
                    $orderby['appid'] = $asc_or_desc;
                    break;
                case 2:
                    $orderby['version'] = $asc_or_desc;
                    break;
                case 5:
                    $orderby['createtime'] = $asc_or_desc;
                    break;
            }


            $searchValue = $search['value'];
            $start = $this->input->post("start");
            $length = $this->input->post("length");
            $data = $this ->app_model->get_i18n($start, $length, $searchValue, $orderby);
            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]["createtime"] = date("Y-m-d  h:i:s", $data['data'][$key]["createtime"]);
            }
            echo json_encode($data);
        }
    }

    private function _get_platform($appid) {
        $platform = "unknow";
        switch ($appid) {
            case 21:
                $platform = "ios";
                break;
            case 22:
                $platform = "android";
                break;
        }

        return $platform;
    }

    public function i18n_upload() {

        if (strtolower($_SERVER["REQUEST_METHOD"]) == 'post') {
            $filename = $_FILES['i18n_file']['name'];
            $ext = substr($filename, strrpos($filename, '.') + 1);
            $version = $this->input->post("version");
            $appid = $this->input->post("appid");
            $platform = $this->_get_platform($appid);
            if ($platform == 'unknow') {
                echo json_encode(array('code'=> 201, 'msg'=> '请选择正确的平台上传'));
                exit;
            }

            if ($ext != 'zip' && $ext != 'apk') {
                echo json_encode(array('code'=> 202, 'msg'=> '请上传正确的文'));

                exit;
            } else {

                $dir = APPPATH."upload/i18n/".$platform. "/";
                $tmp_name = $_FILES['i18n_file']['tmp_name'];
                $file_size = $_FILES['i18n_file']['size'];
                $filename = date('YmdHis', time()) . "_" . $filename;
                $uploadfile = $dir . $filename;//上传后的文件名地址
                move_uploaded_file($tmp_name, $uploadfile);//假如上传到当前目录下
                $objectUrl = "mynt/".ENVIRONMENT. "/". $platform. "/".$filename;
                $res = $this->oss->uploadFile(self::ALI_I18N_BUCKET, $objectUrl,  $uploadfile, '');
                if (!empty($res) && !empty($res['info']['url'])) {

                    $arr = array(
                        'code' => 200,
                        'name' => $filename,
                        'size' => round($file_size / 1048576, 2),

                    );

                    $this->app_model->add_i18n($appid, $version, $filename, $res['info']['url']);
                    echo json_encode($arr);
                } else {
                    echo json_encode(array('code'=> 203, 'msg'=> '上传文件失败'));
                }
            }

        } else {
            $this->showView('app_i18n_upload');
        }
    }

    public function get_i18n_by_id($id) {
        $query = $this->db->get_where(self::TABLE_I18N, array('id' => $id));
        return $query->row_array();
    }

    public function delete_i18n_by_id($id) {
        $this->db->where('id', $id)
            ->delete(self::TABLE_I18N);

        return $this->db->affected_rows();
    }

    public function i18n_delete() {
        $id  = $this->input->post("id");
        $i18n = $this->app_model->get_i18n_by_id($id);
        if (empty($i18n)) {
            echo json_encode(array("code" => 400000, 'msg' => "i18n不存在"));
            exit;
        }

        $platform = $this->_get_platform($i18n['appid']);
        $objectUrl = "mynt/".ENVIRONMENT. "/". $platform. "/".$i18n['filename'];
        $res =  $this->oss->deleteObject('slightech-i18n', $objectUrl);

        if (!empty($res)) {
            $affected_rows = $this ->app_model->delete_i18n_by_id($id);
            if ($affected_rows > 0) {
                echo json_encode(array("code" => 200));
                exit;
            }
        } else {
            echo json_encode(array("code" => 400000, 'msg' => "删除OSS 失败"));
        }
    }

     public function dictionary_type() {
         if (strtolower($_SERVER["REQUEST_METHOD"]) == 'post') {
             $this->load->model('dictionary_model');
             $search = $this->input->post("search");
             $order = $this->input->post("order");
             $orderIndex = $order[0]["column"];
             $asc_or_desc =  $order[0]["dir"];
             $orderby = array();
             switch ($orderIndex) {
                 case 2:
                     $orderby['code'] = $asc_or_desc;
                     break;
                 case 3:
                     $orderby['createtime'] = $asc_or_desc;
                     break;
             }

             $searchValue = $search['value'];
             $start = $this->input->post("start");
             $length = $this->input->post("length");
             $data = $this->dictionary_model->get_dictionary_types($start, $length, $searchValue, $orderby);
             foreach ($data['data'] as $key => $value) {
                 $data['data'][$key]["createtime"] = date("Y-m-d  h:i:s", $data['data'][$key]["createtime"]);
             }
             echo json_encode($data);
         } else {
             $this->showView('app_dictionary_type');
         }
     }

    public function add_dictionary_type() {
        $this->load->model('dictionary_model');
        $id = $this->input->post("id");
        $code  = $this->input->post("code");
        $name = $this->input->post("name");


        if (empty($id)) {
            $existsDtype = $this->dictionary_model->get_dictionary_by_code($code);
        }

        if (!empty($id)) {
            $existsidDtype = $this->dictionary_model->get_dictionary_by_id($id);
            //修改了编码
            if ($existsidDtype['code'] != $code) {
                $existsDtype = $this->dictionary_model->get_dictionary_by_code($code);
            }
        }


        if (!empty($existsDtype)) {
            die(json_encode(array("code"=> 500, "msg"=> '编码已存在')));
        }


        if (empty($id)) {
            $res = $this->dictionary_model->add_dictionary($code, $name);
        } else {
            $res = $this->dictionary_model-> update_dictionary_type_by_id($id, $code, $name);
        }

        if ($res) {
            die(json_encode(array('code'=> 200)));
        } else {
            die(json_encode(array('code'=> 501, 'msg'=> '添加出错')));
        }
    }


    public function delete_dictionary_type() {
        $this->load->model('dictionary_model');
        $id  = $this->input->post("type_id");
        $items = $this->dictionary_model->get_dictionary_items_by_type($id);
        if (!empty($items)) {
            echo json_encode(array("code" => 400000, 'msg' => "该字典类型存在字典项目不可以删除!请先删除字典项目再删除该类型"));
            exit;
        }
        $res = $this->dictionary_model->delete_dictionary_type_by_id($id);

        if ($res) {
            die(json_encode(array('code'=> 200)));
        } else {
            die(json_encode(array('code'=> 501, 'msg'=> '删除出错')));
        }
    }


    public function dictionary_item() {
        if (strtolower($_SERVER["REQUEST_METHOD"]) == 'post') {
            $this->load->model('dictionary_model');
            $search = $this->input->post("search");
            $search_type = $this->input->post("search_type");

            $order = $this->input->post("order");
            $orderIndex = $order[0]["column"];
            $asc_or_desc =  $order[0]["dir"];
            $orderby = array();
            switch ($orderIndex) {
                case 2:
                    $orderby['display_order'] = $asc_or_desc;
                    break;
                case 3:
                    $orderby['type_id'] = $asc_or_desc;
                    break;
                case 8:
                    $orderby['version'] = $asc_or_desc;
                    break;
                case 10:
                    $orderby['createtime'] = $asc_or_desc;
                    break;
            }

            $searchValue = $search['value'];
            $start = $this->input->post("start");
            $length = $this->input->post("length");

           $data =  $this->dictionary_model->get_dictionary_items($start, $length, $searchValue, $search_type, $orderby);
            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]["createtime"] = date("Y-m-d  h:i:s", $data['data'][$key]["createtime"]);
            }

            echo json_encode($data);
        } else {
            $this->load->model('dictionary_model');
            $dictionary_types = $this->dictionary_model->get_dictionary_all_types();
            $this->showView('app_dictionary_item', array('dictionary_types'=> $dictionary_types));
        }
    }

    public function add_dictionary_item() {
        $this->load->model('dictionary_model');
        $id = $this->input->post("id");
        $typeid  = $this->input->post("type_id");
        $display_order  = $this->input->post("display_order");
        $name  = $this->input->post("name");
        $dkey  = $this->input->post("dkey");
        $lang_key  = $this->input->post("lang_key");
        $dvalue  = $this->input->post("dvalue");
        $extra_value  = $this->input->post("extra_value");
        $unit  = $this->input->post("unit");
        $version  = $this->input->post("version");


        if (empty($id)) {
            $exits_item = $this->dictionary_model-> get_dictionary_item_by_key_typeid($dkey, $typeid);
        }

        if (!empty($id)) {
            $exits_id_item = $this->dictionary_model-> get_dictionary_item_by_id($id);
            //修改了键或者类型
            if ( $exits_id_item['dkey'] != $dkey || $exits_id_item['type_id'] != $typeid) {
                $exits_item = $this->dictionary_model-> get_dictionary_item_by_key_typeid($dkey, $typeid);
            }
        }

        if (!empty($exits_item)) {
            die(json_encode(array("code"=> 500, "msg"=> '已存在该键添加失败,请保证同一类型键值唯一')));
        }

        if (empty($id)) {
            $res  = $this->dictionary_model->add_dictionary_item($typeid, $display_order, $name, $dkey, $lang_key, $dvalue, $extra_value, $unit, $version);
        } else {
            $res  = $this->dictionary_model->update_dictionary_item_by_id($id, $typeid, $display_order, $name, $dkey, $lang_key, $dvalue, $extra_value, $unit, $version);
        }

        if ($res) {
            die(json_encode(array('code'=> 200)));
        } else {
            die(json_encode(array('code'=> 501, 'msg'=> '添加出错')));
        }
    }

    public function delete_dictionary_item() {
        $this->load->model('dictionary_model');
        $id  = $this->input->post("id");

        $res = $this->dictionary_model->delete_dictionary_item_by_id($id);
        if ($res) {
            die(json_encode(array('code'=> 200)));
        } else {
            die(json_encode(array('code'=> 501, 'msg'=> '删除出错')));
        }
    }

    public function get_display_order() {
        $typeid  = $this->input->post("typeid");
        $this->load->model('dictionary_model');
        $display_order = $this-> dictionary_model->get_current_display_order($typeid);
        die(json_encode(array('code'=> 200, 'display_order'=>$display_order )));
    }

    public function download_dictionary() {
        $this->load->model('dictionary_model');


        $downloadJson = array();
        $types = $this->dictionary_model->get_dictionary_all_types();
        foreach ($types as $type) {
            $jsonArray = array();
            $jsonArray['code'] = $type['code'];
            $jsonArray['name'] =$type['name'];
            $items = $this->dictionary_model->get_dictionary_items_by_type($type['id']);
            foreach ($items as $item) {
                $ditem = array(
                    'display_order'=> $item['display_order'],
                    'key'=>$item['dkey'],
                    'lang_key'=> $item['lang_key'],
                    'value'=> $item['dvalue'],
                    'version' => $item['version'],
                    'name'=> $item['name'],
                    'unit' => $item['unit'],
                    'extra_value'=> $item['extra_value']
                );

                $jsonArray['items'][] = $ditem;
            }
            $downloadJson [] = $jsonArray;
        }


        Header( "Content-type:   application/octet-stream ");
        Header( "Accept-Ranges:   bytes ");
        header( "Content-Disposition:   attachment;   filename=dictionary.json ");
        header( "Expires:   0 ");
        header( "Cache-Control:   must-revalidate,   post-check=0,   pre-check=0 ");
        header( "Pragma:   public ");
        echo json_encode($downloadJson);
    }
}